package com.github.llyb120.stock.ctrl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ZipUtil;
import com.github.llyb120.json.Arr;
import com.github.llyb120.namilite.NamiBaseController;
import org.springframework.http.HttpEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.github.llyb120.json.Json.a;
import static com.github.llyb120.stock.Ctrl.environment;

public class pack extends NamiBaseController {

    public Object upload() {
        File path = new File(environment.getProperty("uploads.path"));
        if (!path.exists()) {
            path.mkdirs();
        }
        MultipartFile v = $files.get("file");
        if (v == null) {
            return "";
        }
        try {
            String ext = FileUtil.extName(v.getOriginalFilename());
            if (ext.isEmpty()) {
                ext = "unknown";
            }
            File file = new File(path.getAbsolutePath(), IdUtil.objectId() + "." + ext);
            v.transferTo(file);
            return file.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public HttpEntity down() throws IOException {
        File path = new File(environment.getProperty("uploads.path"));
        File[] list = Arrays.stream($request.ss("names").split(","))
                .map(e -> new File(path, e))
                .filter(e -> e.exists())
                .toArray(File[]::new);
        File temp = File.createTempFile("123", "456");
        temp.deleteOnExit();
        ZipUtil.zip(temp, StandardCharsets.UTF_8, false, list);
        for (File file : list) {
            file.delete();
        }
        return download(temp, $request.ss("name") + ".zip");
    }
}
